package com.putable.server;

import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

/**
 * CGWClientHandler runs administrative taks on the clients connected. Also has a copy of the thread pool.
 * @author Event Horizon
 *
 */
public class CGWClientHandler {
        /**
         * Timer timer for iterating through clients for deleting and cleaning
         * up
         */
        private Timer timer;

        /**
         * Instantiates a new CGW Client Handler, and a new timer
         */
        public CGWClientHandler() {
                timer = new Timer();
        }

        /**
         * Creates new collections synchronized list for clientList.
         */
        private static List<CGWClientProxy> clientList = Collections
                        .synchronizedList(new LinkedList<CGWClientProxy>());

        /** Add clients to the client list **/
        public void addClient(CGWClientProxy cp) {
                clientList.add(cp);
        }

        /** Removes a client from the client list **/
        public boolean removeClient(CGWClientProxy cp) {
                return clientList.remove(cp);
        }

        /**
         * Run through every 1 second to perform administrative tasks.
         */
        public void run() {
                System.out.println("CGWServer: Client Handler Run Called");
                timer.schedule(new TimerTask() {

                        @Override
                        public void run() {
                                for (int i = 0; i < clientList.size(); i++) {
                                        CGWClientProxy cp = clientList.get(i);
                                        if (!cp.isConnected()) {
                                                // Kill the guts
                                                cp.killThread();
                                                clientList.remove(cp);
                                                System.out.println("CGWServer: Removed Client "
                                                                + cp.getName()
                                                                + " from List");
                                                cp = null;
                                                System.gc();
                                        }
                                }
                        }
                }, 0, 1000);
        }
}
